<script setup lang="ts">
import type Typed from 'typed.js'
import { useHitokoto, usePoetry, useTyped } from '@/hooks'

import { ceil, random } from 'lodash-es'

const maximRef = ref<HTMLElement>()

useAnimate(maximRef, [{ transform: 'scale(0)' }, { transform: 'scale(1)' }], 1000)

const maximContentRef = ref<HTMLElement | null>(null)

const randomNumber = ceil(random(0, 1, true), 2)

const {
  origin: maximOrigin,
  author: maximAuthor,
  content: maximContent,
  send
} = randomNumber > 0.5 ? await usePoetry() : await useHitokoto()

const typedInstance = ref<Typed | null>(null)
const opacitySwitch = ref(false)
const maxim = reactive({
  origin: maximOrigin.value,

  author: maximAuthor.value
})

const { initTyped } = useTyped({
  instance: typedInstance as Ref<Typed>,
  contentRef: maximContentRef,
  content: maximContent.value,
  callback: () => {
    typedInstance.value?.stop()

    useParentElement(typedInstance.value!.cursor).value?.removeChild(typedInstance.value!.cursor)

    typedInstance.value?.destroy()

    typedInstance.value = null

    opacitySwitch.value = true

    useTimeoutFn(() => {
      opacitySwitch.value = false
      maxim.author = maximAuthor.value
      maxim.origin = maximOrigin.value
    }, 200)

    nextTick(() => {
      initTyped()
    })
  },
  send
})

onMounted(() => {
  initTyped()
})
</script>

<template>
  <div
    ref="maximRef"
    class="maxim relative h-150px min-w-500px flex-col-center origin-center select-none overflow-hidden rounded-1 bg-origin-border backdrop-blur-sm"
  >
    <h2
      class="mb-10px text-24px font-bold transition duration-200 delay-0 ease-linear"
      :class="{ 'opacity-0': opacitySwitch }"
    >
      {{ maxim.origin }}
    </h2>

    <h3
      class="mb-10px text-14px font-bold transition duration-200 delay-0 ease-linear"
      :class="{ 'opacity-0': opacitySwitch }"
    >
      {{ maxim.author }}
    </h3>
    <div class="flex">
      <div
        ref="maximContentRef"
        class="text-16px"
      />
    </div>
  </div>
</template>

<style lang="scss" scoped>
.maxim {
  box-shadow: 0 0 18px #ffffff80;

  &::after {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    content: '';
    background: #fff;
    filter: blur(5px);
    opacity: 0.3;
    z-index: -1;
  }

  &::before {
    content: '';
    position: absolute;
    inset: -20%;
    background: linear-gradient(45deg, #ffffff00 40%, #ffffff70, #ffffff00 60%);
    animation: shark-wrap 3s infinite;
    transform: translateX(-100%);
  }

  @keyframes shark-wrap {
    to {
      transform: translateX(100%);
    }
  }
}
</style>
